<?php

namespace Hilaoyu\LaravelExtend\Services\Auth\Traits;

use Carbon\Carbon;
use Hilaoyu\LaravelExtend\Services\Auth\AbstractModelAuthToken;
use Hilaoyu\LaravelExtend\Services\Auth\AuthService;
use Hilaoyu\Utils\UtilSupport;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;


trait ModelUserWithAuthMultipleTokenTrait
{
    abstract static protected function classNameModelAuthToken();

    protected $_authenticated_token = null;

    /**
     * @return AbstractModelAuthToken
     */
    public function makeModelAuthToken()
    {
        return $token_model = UtilSupport::makeClass(static::classNameModelAuthToken());
    }


    public function setAuthenticatedToken($token){
        $this->_authenticated_token = $token;
    }
    public function getAuthenticatedToken($key='',$default=null){
        $key = trim($key);
        if($key){
            return data_get($this->_authenticated_token,$key,$default);
        }
        return $this->_authenticated_token ?? $default;
    }


    public function clearExpireToken()
    {
        $this->makeModelAuthToken()->where('expire_time', '<=', Carbon::now())->delete();
    }

    public function auth_token_all($platform = '')
    {
        $query = $this->hasMany(
            static::classNameModelAuthToken(),
            'user_id',
            $this->getAuthIdentifierName()
        )->where('model', '=', static::class);
        if ($platform) {
            $query = $query->where('platform', '=', $platform);
        }

        return $query;
    }


    public function auth_token($platform = '', $source = '')
    {

        $platform = trim($platform);
        $source = trim($source);
        if (empty($platform)) {
            $platform = request()->getClientPlatform();
        }
        if (empty($source)) {
            $source = request()->getClientSource();
        }
        $query = $this->hasOne(
            static::classNameModelAuthToken(),
            'user_id',
            $this->getAuthIdentifierName()
        )
            ->where('model', '=', static::class)
            ->where('platform', '=', $platform)
            ->where('source', '=', $source);

        return $query;

    }


    public function generateToken($expire_time = '', $platform = '', $source = '')
    {

        $expire_time = trim($expire_time);
        $platform = trim($platform);
        $source = trim($source);
        
        if (!$token_model = $this->makeModelAuthToken()) {
            return null;
        }
        if (!$this->exists) {
            return null;
        }


        if (!($uid = $this->getAuthIdentifier())) {
            return null;
        }
        //$token = $this->getAttribute('auth_token');
        //if(!$token){
        $token = $token_model->newInstance([
            'user_id' => $uid,
            'model' => static::class,
            //'expire_time' => $expire_time,
            //'platform' => $platform ? $platform : trim(request()->getClientPlatform()),
            //'source' => $source,
        ]);
        //}


        $token->fillPlatform($platform);
//        $token->platform = $platform;
        $token->fillSource($source);
        $token->fillExpireTime($expire_time);
//        dd($token);
        $token = UtilSupport::tryQuiet(function () use ($token) {
            return $token->fillClientIp();
        });

        if (!$token->save()) {
            $this->setError($token->getError());
            return null;
        }
        // 将token信息保存到缓存
        $key = AuthService::GetTokenCahceKeyPrefix().$token->getKey();
        if ($expire_time = data_get($token, 'expire_time')){
            Cache::put($key, $token, Carbon::parse($expire_time));
        }
        return $token;

    }


}
